<template>
	<el-form :hide-required-asterisk="true" :model="changePwdForm" status-icon :rules="rules" ref="changePwdForm"
		label-width="100px" class="change-pwd-form">
		<el-form-item label="旧密码" prop="oldPwd">
			<el-input type="password" v-model="changePwdForm.oldPwd" autocomplete="off"></el-input>
		</el-form-item>
		<el-form-item label="新密码" prop="passowrd">
			<el-input type="password" v-model="changePwdForm.passowrd" autocomplete="off"></el-input>
		</el-form-item>
		<el-form-item label="确认密码" prop="rePwd">
			<el-input type="password" v-model="changePwdForm.rePwd" autocomplete="off"></el-input>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="submitForm('changePwdForm')">提交</el-button>
			<el-button @click="resetForm('changePwdForm')">重置</el-button>
		</el-form-item>
	</el-form>
</template>
<script>
	import {
		changePwd
	} from '@/api/user'
	import Nav from "@/layout/components/nav/nav";
	export default {
		data() {
			var validatePass = (rule, value, callback) => {
				if (value === '') {
					console.log("pass")
				} else {
					if (this.changePwdForm.passowrd !== '') {
						this.$refs.changePwdForm.validateField('rePwd');
					}
					callback();
				}
			};
			var validatePass2 = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请再次输入密码'));
				} else if (value !== this.changePwdForm.passowrd) {
					callback(new Error('两次输入密码不一致!'));
				} else {
					callback();
				}
			};
			return {
				changePwdForm: {
					oldPwd: '',
					password: '',
					rePwd: ''
				},
				rules: {
					oldPwd: [{
						required: true,
						trigger: 'blur',
						message: '请输入旧密码'
					}],
					password: [{
						validator: validatePass,
						trigger: 'blur'
					}],
					rePwd: [{
						validator: validatePass2,
						trigger: 'blur'
					}]
				}
			};
		},
		methods: {
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					const oldPwd = this.$md5(this.changePwdForm.oldPwd)
					const newPwd = this.$md5(this.changePwdForm.rePwd)
					if (valid) {
						changePwd(oldPwd, newPwd)
							.then(res => {
								if (res.code === 1) {
									this.$message({
										message: res.msg,
										type: 'success'
									});
									this.$store.commit("removeToken")
									this.$store.commit("removeInfo")
									this.$router.push("/")
								}
							})
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			}
		}
	}
</script>